﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.DS
{
    public static partial class status
    {
        public static dynamic getDSStatusList(int start, int limit, int eid, string myusername, bool god,
            int? pid, string username, int? lang, int? status)
        {
            var sql = new Sql.SqlDataContext();
            var ss = from s in sql.DSStatus
                     where (god || !s.god) && s.eid == eid
                     select s;
            if (pid != null) ss = ss.Where(row => row.pid == pid);
            if (username != null) ss = ss.Where(row => row.username.ToLower() == username.ToLower());
            if (lang != null) ss = ss.Where(row => row.lang == lang);
            if (status != null) ss = ss.Where(row => row.status == status);

            var total = ss.Count();
            var result = (from s in ss
                          from p in sql.DSProblem
                          from u in sql.User
                          from l in sql.Language
                          where p.eid == eid && p.pid == s.pid && u.username == s.username && l.code == s.lang
                          orderby s.rid descending
                          let allowCode = s.username == myusername
                          select new
                          {
                              s.eid,
                              s.rid,
                              s.pid,
                              problemTitle = p.title,
                              s.username,
                              u.nickname,
                              submitTime = s.submitTime.toTimeString(),
                              lang = l.title,
                              langCode = s.lang,
                              codeLen = s.code.Length,
                              allowCode,
							  exeTime = god || s.status == 3 ? s.exeTime : null,
							  exeMem = god || s.status == 3 ? s.exeMem : null,
                              status = Core.status.status2String(s.status),
                              statusCode = s.status,
                              reInfo = allowCode || god ? Core.status.reCode2String(s.reCode) : null,
                              reCode = allowCode || god ? Core.status.reCode2Hex(s.reCode) : null,
                              ceInfo = allowCode || god ? s.ceInfo : null,
                              s.god
                          }).Skip(start).Take(limit);
            return new
            {
                success = true,
                total,
                result
            };
        }
    }
}
